import React, {useEffect, useRef, useState} from "react";
import axios from "axios";
import {Button, PageHeader, Steps, Form, Input, Select, message, notification} from 'antd';
import NewsEditor from "../../../components/news-manage/NewsEditor";

import style from './NewsAdd.module.css';
import {useNavigate} from "react-router-dom";

const { Step } = Steps;
const { Option } = Select;

export default function NewsAdd() {

    const [current, setCurrent] = useState(0);
    const [categories, setCategories] = useState([]);
    const basicFormRef= useRef(null);

    const [ formInfo, setFormInfo ]= useState({});
    const [ newsContent, setNewsContent ]= useState("");
    const navigate= useNavigate();

    useEffect(()=>{
        axios.get('/api/categories').then(response=>{
            setCategories(response.data);
        })
    }, []);

    // 下一步
    const handleNext= ()=>{
        if(current===0) {
            basicFormRef.current.validateFields().then(res=>{
                // console.log(res);
                setCurrent(current+1);
                setFormInfo(res);
            }).catch(error=>{
                message.error('表单内容不能为空');
            });
        } else {
            // console.log(formInfo, newsContent);
            if(newsContent.trim()==="" || newsContent.trim()==="<p></p>") {
                message.error('新闻内容不能为空');
            } else {
                setCurrent(current+1);
            }
        }
    }

    const User = JSON.parse(localStorage.getItem('token'))
    // 保存至草稿箱 或 提交审核
    const handleSaveAudit= (auditState)=>{
        // auditState===0 ? console.log('保存至草稿箱') : console.log('提交审核');

        axios.post('/api/news', {
            "title": formInfo.title,  // 新闻标题
            "categoryId": formInfo.categoryId,  // 新闻分类id
            "content": newsContent,  // 新闻正文
            "region": User.region ? User.region : '全球',  // 地区
            "author": User.username, // 作者名字
            "roleId": User.roleId,   // 作者角色id
            "auditState": auditState,  // 0草稿箱  1待审核  2审核通过  3审核不通过
            "publishState": 0,  // 0待发布  1已发布  2已下线
            "createTime": Date.now(),  // 创建时间
            "star": 0,  // 点赞数量
            "view": 0,  // 访问数量
            "comment": 0,  // 评论数量
            // "publishTime": 0  // 发布时间
        }).then(response=>{
            // console.log(response);
            if(auditState===0) {
                notification.info({
                    message: `通知`,
                    description: `您可以到草稿箱中查看${formInfo.title}这篇新闻`,
                    placement: 'bottomRight',
                });
                navigate('/news-manage/draft');  // 草稿箱
            } else {
                notification.info({
                    message: `通知`,
                    description: `您可以到审核列表中查看${formInfo.title}这篇新闻`,
                    placement: 'bottomRight',
                });
                navigate('/audit-manage/list');  // 审核列表
            }
        });
    }

    return (
        <div>
            <PageHeader title="撰写新闻" />

            <div style={{padding: '20px'}}>
                <Steps current={current}>
                    <Step title="基本信息" description="新闻标题 新闻分类" />
                    <Step title="新闻内容" description="新闻主体" />
                    <Step title="新闻提交" description="保存草稿或提交审核" />
                </Steps>
            </div>


            <div className={style['content-container']}>
                <div className={current===0 ? style.active : style.hidden}>
                    <Form labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} ref={ basicFormRef }>
                        <Form.Item name="title" label="新闻标题" rules={[{ required: true, message: '请输入文章标题' }]}>
                            <Input placeholder="新闻标题" />
                        </Form.Item>
                        <Form.Item name="categoryId" label="新闻分类" rules={[{ required: true, message: '请选择文章分类' }]}>
                            <Select placeholder="新闻分类">
                                {
                                    categories.map(item=><Option value={item.id} key={item.id}>{item.value}</Option>)
                                }
                            </Select>
                        </Form.Item>
                    </Form>
                </div>

                <div className={current===1 ? style.active : style.hidden}>
                    <NewsEditor getContent={ (htmlContent)=>{
                        // console.log(htmlContent);
                        setNewsContent(htmlContent);
                    }}/>
                </div>

                <div className={current===2 ? [style.active, style['news-show']] : style.hidden} >
                    <h1 className={style['news-title']}>{formInfo.title}</h1>
                    <div className={style['news-subtitle']}>
                        <span>新闻分类：{categories.filter(item=>item.id===formInfo.categoryId)[0]?.value}</span>
                        <span>作者：{User.username}</span>
                    </div>
                    <div dangerouslySetInnerHTML={{__html: newsContent}} className={style['news-content']}></div>
                </div>
            </div>

            <div className={style['news-button-wrapper']}>
                {
                    current===2 && <span>
                        <Button type="primary" style={{margin: '0 10px'}} onClick={()=>handleSaveAudit(0)}>保存草稿</Button>
                        <Button danger style={{margin: '0 10px'}} onClick={()=>handleSaveAudit(1)}>提交审核</Button>
                    </span>
                }
                {
                    current>0 && <Button onClick={()=>setCurrent(current-1)} style={{margin: '0 10px'}}>上一步</Button>
                }
                {
                    current<2 && <Button type="primary" onClick={()=>handleNext()} style={{margin: '0 10px'}}>下一步</Button>
                }
            </div>
        </div>
    );
}
